import { Flex, Image, List, message } from 'antd';
import React, { useEffect, useMemo, useState } from 'react';

import ygtImg from '@/assets/imgs/ygt.ico';
import { bindAccount, fetchAccount, getAccountCaptcha, unBindAccount } from '@/apis/account';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';

const BindingView: React.FC = () => {

  const [ygtAccount, setYgtAccount] = useState<any>();

  const [code, setCode] = useState();
  const [uuid, setUuid] = useState();
  const [open, setOpen] = useState(false);
  const [openEdit, setOpenEdit] = useState(false);

  const {run: runBind, loading: loadingBind} = useRequest(bindAccount, {
    manual: true,
    onSuccess: ( data ) => {
      if (data) {
        message.success(data);
        setOpenEdit(false);
      }
    }
  });

  const {run: runUnBind, loading: loadingUnbind} = useRequest(unBindAccount, {
    manual: true,
    onSuccess: ( data ) => {
      if (data) {
        message.success(data);
        setOpen(false);
        setYgtAccount(null);
      }

    }
  });


  const {run: runCode, loading: loadingCode} = useRequest(getAccountCaptcha, {
    manual: true,
    onSuccess: ( data ) => {
      if (data) {
        const {img, uuid} = data;
        setCode(img);
        setUuid(uuid);
      }
    }
  });

  useEffect(() => {
    // 获取当前绑定信息
    fetchAccount().then(( res: any ) => {
      if (res.code === 200) {
        let resData = res.data;
        if (Array.isArray(resData)) {
          let account = resData.find(( item: any ) => item.accountType === 1);
          if (account) {
            setYgtAccount(account);
          }
        }
      }
    });
  }, []);

  const bindElement = useMemo(() => {
    return <ModalForm title={ygtAccount ? '修改一港通账号' : '绑定一港通账号'}
                      initialValues={{
                        uuid: uuid,
                      }}
                      open={openEdit}
                      trigger={<a key="Bind">{ygtAccount ? '修改' : '绑定'}</a>}
                      modalProps={{
                        destroyOnHidden: true,
                      }}
                      width={400}
                      onOpenChange={( visible ) => {
                        setOpenEdit(visible);
                        if (visible) {
                          runCode();
                        }
                      }}
                      onFinish={async ( values ) => {
                        runBind(values);
                      }}
    >
      <ProFormText name={'uuid'} hidden></ProFormText>
      <ProFormText name={'username'} label={'用户名'} rules={[{required: true, message: '请输入用户名'}]}></ProFormText>
      <ProFormText name={'password'} label={'密码'} rules={[{required: true, message: '请输入密码'}]}></ProFormText>
      <Flex align={'end'} justify={'space-between'}>
        <ProFormText
          formItemProps={{
            className: 'mb-0 flex-1'
          }}
          name="code"
          label={'验证码'}
          rules={[{required: true, message: '请输入验证码'}]}>
        </ProFormText>
        <Image className="cursor-pointer" width={100} height={40} src={code} preview={false} onClick={runCode}/>
      </Flex>
    </ModalForm>;
  }, [code, uuid, openEdit, ygtAccount]);

  const unBindElement = useMemo(() => {
    return <ModalForm title={`解除一港通账号(${ygtAccount?.username})`}
                      initialValues={{
                        uuid: uuid,
                      }}
                      open={open}
                      onOpenChange={( visible ) => {
                        setOpen(visible);
                      }}
                      trigger={<a key="Edit">解绑</a>}
                      modalProps={{
                        destroyOnHidden: true,
                      }}
                      width={400}
                      onFinish={async ( values ) => {
                        runUnBind(values);
                      }}
    >
      <ProFormText.Password name={'password'}
                            rules={[{required: true, message: '请输入密码'}]}
                            allowClear
                            placeholder="请输入密码"/>
    </ModalForm>;
  }, [code, uuid, ygtAccount, open]);


  const getData = () => [
    {
      title: '绑定一港通',
      description: ygtAccount ? ygtAccount.username : '当前未绑定一港通账号',
      actions: (ygtAccount ? [unBindElement] : [bindElement]),
      avatar: <Image width={32} src={ygtImg} preview={false}/>,
    },
    // {
    //   title: '绑定支付宝',
    //   description: '当前未绑定支付宝账号',
    //   actions: [<a key="Bind">绑定</a>],
    //   avatar: <AlipayOutlined className="alipay" />,
    // },
    // {
    //   title: '绑定钉钉',
    //   description: '当前未绑定钉钉账号',
    //   actions: [<a key="Bind">绑定</a>],
    //   avatar: <DingdingOutlined className="dingding" />,
    // },
  ];

  return (
    <List
      itemLayout="horizontal"
      dataSource={getData()}
      renderItem={( item ) => (
        <List.Item actions={item.actions}>
          <List.Item.Meta
            avatar={item.avatar}
            title={item.title}
            description={item.description}
          />
        </List.Item>
      )}
    />
  );
};

export default BindingView;
